package com.aifeng.hassan_food.sale

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import com.aifeng.base.BaseActivity
import com.aifeng.base.addItems
import com.aifeng.base.setHtmlSmall
import com.aifeng.common_ui.base.find
import com.aifeng.common_ui.base.getColorEx
import com.aifeng.common_ui.base.gone
import com.aifeng.common_ui.base.oneClick
import com.aifeng.common_ui.helper.*
import com.aifeng.hassan_food.R
import com.aifeng.hassan_food.WebActivity
import com.aifeng.hassan_food.login.LoginActivity
import com.aifeng.model.CommonData
import com.aifeng.utils.DialogHelper.showCarDialog
import com.aifeng.utils.DialogHelper.showParamDialog
import com.aifeng.utils.bindLifeCycle
import com.aifeng.utils.getExtra
import com.aifeng.utils.subscribeByFinally
import com.aifeng.utils.subscribeByNoError
import com.aifeng.view.ImageAdapter
import com.aifeng.viewmodel.GoodsViewModel
import com.jeremyliao.liveeventbus.LiveEventBus
import com.jeremyliao.liveeventbus.utils.observe
import com.zhpan.bannerview.BannerViewPager
import com.zhpan.bannerview.BaseViewHolder
import com.zhpan.indicator.enums.IndicatorSlideMode
import com.zhpan.indicator.enums.IndicatorStyle
import kotlinx.android.synthetic.main.activity_detail.*
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONArray
import org.json.JSONObject
import org.koin.androidx.viewmodel.ext.android.getViewModel

class DetailActivity : BaseActivity() {

    private lateinit var mViewPager: BannerViewPager<String, BaseViewHolder<String>>
    private lateinit var mGoodsId: String
    private val mImages = ArrayList<String>()
    private val mParams = ArrayList<Pair<String, String>>()
    private var mData: CommonData? = null
    private var mPrice = "0.00"
    private var mOrginPrice = "0.00"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_detail)
        setTransparentAndToolbar(isDarkFont = false)
        initTitle()

        getData()
    }

    override fun getViewModel() = getViewModel<GoodsViewModel>()

    @SuppressLint("SetJavaScriptEnabled")
    override fun initTitle(title: String, name: String, divider: Boolean) {
        mGoodsId = intent.getExtra("id")
        initViewPager()
        detail_yuan.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
        detail_hot.gone()

        detail_option_ll.oneClick { if (mParams.isNotEmpty()) showParamDialog(mParams) }
        detail_service.oneClick { startActivity<WebActivity>("title" to "在线客服") }
        detail_bt01.oneClick {
            if (isLogin) {
                showDialog {
                    toast("添加购物车成功！")
                    LiveEventBus.get("carList").post("refresh")
                    LiveEventBus.get("updateNum").post(it)
                }
            } else startActivity<LoginActivity>()
        }
        detail_bt02.oneClick {
            mData?.let {
                if (isLogin) {
                    showCarDialog(
                        if (mImages.isEmpty()) "" else mImages[0],
                        mPrice,
                        mOrginPrice,
                        "下单",
                        it.specs,
                        it.specstype,
                        "立即下单"
                    ) { result ->
                        it.num = result
                        val jsonData = JSONArray().put(
                            JSONObject().apply {
                                put("goodsid", mGoodsId)
                                put("num", result)
                            }
                        ).toString()

                        startActivity<ConfirmActivity>(
                            "json" to jsonData,
                            "data" to ArrayList<CommonData>().apply { add(it) }
                        )
                    }
                } else startActivity<LoginActivity>()
            }
        }

        detail_web.apply {
            //支持javascript
            settings.javaScriptEnabled = true
            //设置可以支持缩放
            settings.setSupportZoom(false)
            //自适应屏幕
            settings.loadWithOverviewMode = true
            settings.useWideViewPort = true

            //设置出现缩放工具
            settings.builtInZoomControls = true
            settings.displayZoomControls = false

            //设置是否使用缓存
            settings.setAppCacheEnabled(true)
            settings.domStorageEnabled = true
        }

        observe("otherLogin") { updateData() }
    }

    private fun initViewPager() {
        mViewPager = find(R.id.detail_banner)
        mViewPager.apply {
            layoutParams = ConstraintLayout.LayoutParams(
                getScreenWidth(),
                getScreenWidth()
            )

            adapter = ImageAdapter()
            setIndicatorStyle(IndicatorStyle.ROUND_RECT)
            setIndicatorSlideMode(IndicatorSlideMode.SCALE)
            setIndicatorSliderGap(dp2px(4f))
            setIndicatorHeight(dp2px(4f))
            setIndicatorSliderColor(
                getColorEx(R.color.white),
                getColorEx(R.color.colorAccent)
            )
            setIndicatorSliderWidth(dp2px(4f), dp2px(10f))
            setInterval(5000)
            setScrollDuration(500)
            setOnPageClickListener {

            }
        }.create()
    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getDetail(mGoodsId)
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    mData = it
                    updateData()
                }
            )
    }

    @SuppressLint("SetTextI18n")
    private fun updateData() {
        mData?.let {
            mPrice = it.price
            mOrginPrice = it.orgprice

            detail_name.text = it.goodname
            detail_price.text =
                setHtmlSmall(
                    "¥ ${if (isLogin) mPrice.formatDecimalWhenHave() else mOrginPrice.formatDecimalWhenHave()}",
                    "¥"
                )

            detail_yuan.apply {
                visibility = if (isLogin) View.VISIBLE else View.GONE
                detail_yuan.text = "原价 ¥ ${mOrginPrice.formatDecimalWhenHave()}"
            }
            detail_set.visibility = if (it.specstype == "package") View.VISIBLE else View.GONE
            detail_weight.text = "规格：${it.specs}"

            val goodsImg = it.goodimg
            if (goodsImg.isNotEmpty()) {
                mImages.addItems(goodsImg.split(","))
                mViewPager.refreshData(mImages)
            }

            if (it.content.isWeb()) {
                val str = "<!doctype html><html>\n" +
                        "<meta charset=\"utf-8\">" +
                        "<style type=\"text/css\">" +
                        "body{ padding:0; margin:0; }\n" +
                        ".con{ width:95%; text-align:center; color:#666; padding:0.5em 0; font-size:0.92em; line-height:1.8em; }\n" +
                        ".con h1,h2,h3,h4,h5,h6{ font-size:1em; }\n " +
                        "img{ width:100%; height:auto; }\n" +
                        "*{ max-width:100% !important; }\n" +
                        "</style>\n" +
                        "<body style=\"padding:0; margin:0; \">" +
                        "<img src=\"${it.content}\"/>" +
                        "</body>" +
                        "</html>"

                detail_web.loadDataWithBaseURL("", str, "text/html", "utf-8", "")
            } else {
                val str = "<!doctype html><html>\n" +
                        "<meta charset=\"utf-8\">" +
                        "<style type=\"text/css\">" +
                        "body{ padding:0; margin:0; }\n" +
                        ".con{ width:95%; text-align:center; color:#666; padding:0.5em 0; font-size:0.92em; line-height:1.8em; }\n" +
                        ".con h1,h2,h3,h4,h5,h6{ font-size:1em; }\n " +
                        "img{ width:100%; height:auto; }\n" +
                        "*{ max-width:100% !important; }\n" +
                        "</style>\n" +
                        "<body style=\"padding:0; margin:0; \">" +
                        it.content +
                        "</body>" +
                        "</html>"

                detail_web.loadDataWithBaseURL("", str, "text/html", "utf-8", "")
            }

            mParams.apply {
                if (it.burden.isNotEmpty()) add(Pair("配料表", it.burden))
                if (it.netcount.isNotEmpty()) add(Pair("净含量", it.netcount))
                if (it.expirationdate.isNotEmpty()) add(Pair("保质期", it.expirationdate))
                if (it.store.isNotEmpty()) add(Pair("储存条件", it.store))
                if (it.producedate.isNotEmpty()) add(Pair("生产日期", it.producedate.toFormat()))
                if (it.savemethod.isNotEmpty()) add(Pair("保存方法", it.savemethod))
                if (it.eatmethod.isNotEmpty()) add(Pair("食用方法", it.eatmethod))
                if (it.producepermit.isNotEmpty()) add(Pair("生产许可", it.producepermit))
                if (it.execute.isNotEmpty()) add(Pair("执行标准", it.execute))
                if (it.retailer.isNotEmpty()) add(Pair("监制商", it.retailer))
                if (it.producer.isNotEmpty()) add(Pair("生产商", it.producer))
                if (it.address.isNotEmpty()) add(Pair("地址", it.address))
            }

            val hintList = ArrayList<String>()
            mParams.mapTo(hintList) { inner -> inner.first }
            if (hintList.isNotEmpty()) detail_option.text = hintList.joinToString("，")
        }
    }

    private fun showDialog(onFinish: (String) -> Unit) {
        mData?.let {
            showCarDialog(
                if (mImages.isEmpty()) "" else mImages[0],
                mPrice,
                mOrginPrice,
                "购物车",
                it.specs,
                it.specstype
            ) { num ->
                getViewModel().addToCar(
                    mGoodsId,
                    getString("userId"),
                    num.toNotInt()
                )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByNoError(
                        event = getViewModel(),
                        onSuccess = { result -> onFinish.invoke(result) }
                    )
            }
        }
    }

    override fun onPause() {
        super.onPause()
        mViewPager.stopLoop()
        detail_web.onPause()
    }

    override fun onResume() {
        super.onResume()
        mViewPager.startLoop()
        detail_web.onResume()
    }

    override fun onDestroy() {
        super.onDestroy()
        detail_web.destroy()
    }


}
